/**
 * @date 2006-5-12 17:21:50
 *
 */
package org.nanhill.moo.dao.hibernate;

import java.util.List;

import org.nanhill.commons.pattern.search.SearchConstant;
import org.nanhill.commons.pattern.search.SearchException;
import org.nanhill.commons.pattern.search.SearchVisitor;
import org.nanhill.moo.dao.FavorDao;
import org.nanhill.moo.domain.Favor;
import org.nanhill.moo.domain.query.FavorQuery;
import org.nanhill.moo.domain.search.favor.FavorAuthorIdCriterion;
import org.nanhill.moo.domain.search.favor.FavorCategoryIdCriterion;
import org.nanhill.moo.domain.search.favor.FavorCostIdCriterion;
import org.nanhill.moo.domain.search.favor.FavorIdDescCriterion;
import org.nanhill.moo.domain.search.favor.HibernateFavorCountVisitor;
import org.nanhill.moo.domain.search.favor.HibernateFavorListVisitor;
import org.nanhill.support.hibernate.HibernateEntityManager;

/**
 * @author alin [xalinx at gmail dot com]
 * 
 */
public class FavorDaoImpl extends HibernateEntityManager<Favor, Long> implements
		FavorDao {

	public void deleteById(long id) {
		update("delete Favor where id = ?", id);
	}

	public List<Favor> findPart(FavorQuery query) throws SearchException {
		HibernateFavorListVisitor visitor = new HibernateFavorListVisitor(
				getSession(), Favor.class, query.getStart(), query
						.getPageSize());
		addCriterions(visitor, query.getCostId(), query.getUserId(), query
				.getCategoryId());
		addOrderCriterions(visitor, query.getFavorIdOrder());
		visitor.doSearch();
		return visitor.getFavorList();
	}

	public long findCount(FavorQuery query) throws SearchException {
		HibernateFavorCountVisitor visitor = new HibernateFavorCountVisitor(
				getSession());
		addCriterions(visitor, query.getCostId(), query.getUserId(), query
				.getCategoryId());
		visitor.doSearch();
		return visitor.getCount();
	}

	private void addCriterions(SearchVisitor visitor, final long costId,
			final long userId, final long cagetoryId) throws SearchException {
		if (costId != 0)
			visitor.addCriterion(new FavorCostIdCriterion(costId));
		if (userId != 0)
			visitor.addCriterion(new FavorAuthorIdCriterion(userId));
		if (cagetoryId != 0)
			visitor.addCriterion(new FavorCategoryIdCriterion(cagetoryId));
	}

	private void addOrderCriterions(SearchVisitor visitor, final boolean idOrder)
			throws SearchException {
		if (SearchConstant.DESC == idOrder) {
			visitor.addCriterion(FavorIdDescCriterion.getSingle());
		}
	}

}
